﻿using UnityEngine;
using UnityEditor;

public class MultiSelectWindow : EditorWindow
{
    private Rect selectionRect;
    private Vector2 mouseStartPosition;
    private bool isSelecting;

    [MenuItem("Window/Multi Select")]
    public static void ShowWindow()
    {
        GetWindow<MultiSelectWindow>("Multi Select");
    }

    private void OnGUI()
    {
        // 处理鼠标事件
        HandleMouseEvents();

        // 绘制选择框
        if (isSelecting)
        {
            DrawSelectionRect();
        }

        if (GUI.changed) Repaint();
    }

    private void HandleMouseEvents()
    {
        Event e = Event.current;

        // 鼠标左键按下时开始选择
        if (e.type == EventType.MouseDown && e.button == 0)
        {
            Debug.Log(e.type);

            isSelecting = true;
            mouseStartPosition = e.mousePosition;
            selectionRect.Set(mouseStartPosition.x, mouseStartPosition.y, 0, 0);
            Repaint();
        }

        // 鼠标移动时更新选择框
        if (e.type == EventType.MouseDrag && isSelecting)
        {
            Debug.Log(e.type);

            selectionRect.xMin = Mathf.Min(mouseStartPosition.x, e.mousePosition.x);
            selectionRect.xMax = Mathf.Max(mouseStartPosition.x, e.mousePosition.x);
            selectionRect.yMin = Mathf.Min(mouseStartPosition.y, e.mousePosition.y);
            selectionRect.yMax = Mathf.Max(mouseStartPosition.y, e.mousePosition.y);
            Repaint();
        }

        // 鼠标左键释放时结束选择
        if (e.type == EventType.MouseUp && e.button == 0)
        {
            Debug.Log(e.type);

            isSelecting = false;
            // 这里可以添加选择物体的逻辑
            Debug.Log("Selection ended.");
            Repaint();
        }
    }

    private void DrawSelectionRect()
    {
        // 绘制选择框
        EditorGUI.DrawRect(selectionRect, new Color(0.5f, 0.5f, 1f, 0.3f));
        Handles.BeginGUI();
        Handles.DrawSolidRectangleWithOutline(selectionRect, new Color(0.5f, 0.5f, 1f, 0.3f), Color.blue);
        Handles.EndGUI();
    }
}
